
from django.core.files.storage import Storage
from fdfs_client.client import  Fdfs_client
from django.utils.deconstruct import deconstructible

from mall import settings

@deconstructible
class FastDFSStorage(Storage):

    def __init__(self,conf_path=None,ip=None):
        if not conf_path:
            conf_path = settings.FDFS_STORAGE_CONF_PATH
        self.conf_path = conf_path

        if not ip:
            ip = settings.FDFS_STORAGE_URL
        self.ip = ip

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content, max_length=None):
        client = Fdfs_client(self.conf_path)
        file_data = content.read()
        resp_data = client.upload_by_buffer(file_data)

        if resp_data.get('Status')=='Upload successed.':
            url = resp_data.get('Remote file_id')
            return url
        else:
            raise Exception('上传失败')

    def exists(self, name):
        return False

    def url(self, name):
        return self.ip + name